/*=====================================================================*
 *                   Copyright (C) 2011 Paul Mineiro                   *
 * All rights reserved.                                                *
 *                                                                     *
 * Redistribution and use in source and binary forms, with             *
 * or without modification, are permitted provided that the            *
 * following conditions are met:                                       *
 *                                                                     *
 *     * Redistributions of source code must retain the                *
 *     above copyright notice, this list of conditions and             *
 *     the following disclaimer.                                       *
 *                                                                     *
 *     * Redistributions in binary form must reproduce the             *
 *     above copyright notice, this list of conditions and             *
 *     the following disclaimer in the documentation and/or            *
 *     other materials provided with the distribution.                 *
 *                                                                     *
 *     * Neither the name of Paul Mineiro nor the names                *
 *     of other contributors may be used to endorse or promote         *
 *     products derived from this software without specific            *
 *     prior written permission.                                       *
 *                                                                     *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND              *
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,         *
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES               *
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE             *
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER               *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,                 *
 * INCIDENTAL, SPECIAL, EXDATAPLARY, OR CONSEQUENTIAL DAMAGES            *
 * (INCLUDING, BUT NOT LIMITED TO, PROCURDATAENT OF SUBSTITUTE           *
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR                *
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF          *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           *
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY              *
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE             *
 * POSSIBILITY OF SUCH DAMAGE.                                         *
 *                                                                     *
 * Contact: Paul Mineiro <paul@mineiro.com>                            *
 *=====================================================================*/

#ifndef __PARSE_H__
#define __PARSE_H__

#include "MurmurHash3.h"
#include "rating.h"
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static uint64_t
hash (const char* s)
{
  uint64_t hv[2];
  const char* p;

  for (hv[0] = 0, p = s; isdigit (*p); ++p)
    {
      hv[0] *= 10;
      hv[0] += *p - '0';
    }
  
  if (*p == '\0')
    {
      return hv[0];
    }

  MurmurHash3_x64_128 (s, strlen (s), 0, hv);
  return hv[0];
}

static void
eat_white (char** p)
{
  while (isspace (**p))
    {
      ++*p;
    }
}

static void
eat_nonwhite (char** p)
{
  while (! isspace (**p) && **p != '\0')
    {
      ++*p;
    }
}

static int
parse_unsigned_int (char**       p,
                    unsigned int maxval,
                    uint64_t     lineno)
{
  char* endptr;
  int val = strtol (*p, &endptr, 0);

  (void) lineno;

  if (*endptr == '\0' || isspace (*endptr))
    {
      if (val >= 0 && val < (int) maxval)
        {
          *p = endptr;
          return val;
        }
      else
        {
/*
          fprintf 
            (stderr,
             "error: value %d outside allowed range [0, %u] at line %lu\n",
             val,
             maxval,
             lineno);
*/
        }
    }
  else
    {
/*
      fprintf (stderr,
               "error: malformed integer constant at line %lu\n",
               lineno);
*/
    }

  return -1;
}

/* clamp? tag| worker:label* */

static int
parse_ratings (FILE*            in,
               Rating*          ratings,
               unsigned int     max_ratings,
               char*            tag,
               unsigned int     max_tag,
               int*             clamp,
               uint64_t         lineno,
               unsigned int     n_labels,
               unsigned int     n_workers)
{
  char buf[65536];

  if (fgets (buf, sizeof (buf), in) == NULL)
    {
/*
      fprintf (stderr, 
               "error: can't read buf at input line %lu: %s\n",
               lineno,
               strerror (errno));
*/

      return -1;
    }

  char* bufptr = buf;

  if (isspace (*bufptr))
    {
      *clamp = -1;
    }
  else
    {
      *clamp = parse_unsigned_int (&bufptr, n_labels, lineno);

      if (*clamp == -1)
        {
          return -1;
        }
    }

  eat_white (&bufptr);
  char* pipe = strchr (bufptr, '|');

  if (pipe == NULL)
    {
      return -1;
    }

  *pipe = '\0';
  strncpy (tag, bufptr, max_tag);
  tag[max_tag - 1] = '\0';

  bufptr = pipe + 1;

  unsigned int r;
  for (eat_white (&bufptr), r = 0;
       *bufptr != '\0' && r < max_ratings;
       eat_white (&bufptr), ++r)
    {
      char* worker = bufptr;

      eat_nonwhite (&bufptr);
      if (*bufptr != '\0') { *bufptr++ = '\0'; }

      char* colon = strrchr (worker, ':');

      if (! colon)
        {
/*
          fprintf (stderr, 
                   "error: no label for worker '%s' at input line %lu\n",
                   worker,
                   lineno);
*/

          return -1;
        }

      *colon++ = '\0';
      int label = parse_unsigned_int (&colon, n_labels, lineno);

      if (label < 0)
        {
          return -1;
        }

      ratings[r].worker = hash (worker) % n_workers;
      ratings[r].rating = label;
    }

  if (*bufptr != '\0')
    {
/*
      fprintf (stderr,
               "error: too many ratings at input line %lu\n",
               lineno);
*/

      return -1;
    }

  return r;
}

#endif /* __PARSE_H__ */
